<!-- 
  @author : andy
  @description : 混合菜单组件
-->
<template>
  <div class="header-sidebar">
    <div class="layout-menu">
      <a-menu mode="horizontal" v-model:selected-keys="selectedKeys" :inline-indent="12" @click="onClick">
        <a-menu-item v-for="item in accessStore.accessMenus" :key="item.code" :title="false">
          <template #icon>
            <img v-if="item.icon" class="menu-icon" :src="item.icon" />
          </template>
          {{item.name}}
        </a-menu-item>
      </a-menu>
    </div>
  </div>
</template>

<script lang='ts' setup>
import { useAccessStore } from '@/stores/access/access';
import type { AccessMenuItem } from '@/stores/access/types';
import { getPathByKey } from '@/utils/tree';
import type { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
import { ref, watchEffect } from 'vue';
import { useConfigStore } from '@/stores/configs/config';
import { useRoute , useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
const configStore = useConfigStore();
const { config } = storeToRefs(configStore);
const route = useRoute();
const router = useRouter();
const selectedKeys = ref<string[]>([]);
const accessStore = useAccessStore();
const onClick = ({key}: MenuInfo) => {
  if (config.value.secondMenu.enable) {
    accessStore.setSecondMenusByCode(key as string);
  } else {
    accessStore.setMixedSidebarMenusByCode(key as string);
  }
  const currentMenu = accessStore.accessMenus.filter(item => item.code === key)[0];
  if (currentMenu.children.length === 0) {
    router.push({
      path : currentMenu.path
    })
  }
}
const getCurrentMenu = (): AccessMenuItem | null => {
  let current: AccessMenuItem | null = null;
  const go = (tree: AccessMenuItem[]) => {
    tree.forEach(item => {
      if (item.children.length > 0) {
        go(item.children);
      } else {
        if (item.path === route.path) {
          current = item;
        }
      }
    })
  }
  go(accessStore.accessMenus);
  return current;
}
watchEffect(() => {
  const current = getCurrentMenu();
  if (current) {
    const pathList = getPathByKey(current.code , accessStore.accessMenus , {keyProp : 'code'});
    if (pathList.length > 0) {
      const code = pathList[0].code;
      selectedKeys.value = [code];
      if (config.value.secondMenu.enable) {
        accessStore.setSecondMenusByCode(code);
      } else {
        accessStore.setMixedSidebarMenusByCode(code);
      } 
    }
  }
});
</script>

<style lang='less' scoped>
.header-sidebar {
  display: flex;
  align-items: center;
  width: 100%;
  flex-wrap: nowrap;
  flex: 1;
  .layout-menu {
    flex: 1;
    height: 100%;
    .menu-icon {
      width: 0.16rem;
      height: 0.16rem;
      object-fit: cover;
      transition: all 0.3s;
    }
  }
}
</style>